﻿Imports System.Windows.Controls
Imports Microsoft.LightSwitch.Threading
Imports DocumentToolkit.Client
Imports System.Runtime.InteropServices.Automation
Imports FirstFloor.Documents.Pdf
Imports System.Text


Namespace LightSwitchApplication

    Public Class MediaDetail

        Private Sub Media_Loaded(succeeded As Boolean)
            ' Write your code here.
            Me.SetDisplayNameFromEntity(Me.Media)
            If Me.Media.FileName.EndsWith(".pdf") Then
                Me.FindControl("File").IsVisible = True
                Me.FindControl("FileForDisplay").IsVisible = False
            Else
                Me.FindControl("file").IsVisible = False
                Me.FindControl("FileForDisplay").IsVisible = True
            End If
        End Sub

        Private Sub Media_Changed()
            ' Write your code here.
            Me.SetDisplayNameFromEntity(Me.Media)
        End Sub

        Private Sub MediaDetail_Saved()
            ' Write your code here.
            Me.SetDisplayNameFromEntity(Me.Media)
        End Sub

        Private Sub Download_Execute()
            ' Write your code here.
            Dispatchers.Main.Invoke(
            Sub()
                Dim dlg = New SaveFileDialog()
                If dlg.ShowDialog = True Then
                    Dim stream = dlg.OpenFile
                    Using (stream)
                        ' save original uploaded File
                        stream.Write(Me.Media.File, 0, Me.Media.File.Length)
                    End Using
                End If
            End Sub)
        End Sub

        Private Sub Upload_Execute()
            ' Write your code here.
            Dim file = SelectFile()
            If Not file Is Nothing Then
                'Dim reader = DocumentReader.Create(file)
                'Using reader
                '' update file binary
                'Me.Media.File = reader.ToBinary
                '' update xps binary
                'Me.Media.FileXps = Nothing
                'If reader.RequiresConversionToXps Then
                '' conversion needed, get the XPS binary
                'Me.Media.FileXps = reader.ToXpsBinary
                'End If
                'End Using

                Dim bData As Byte()
                Dim br As BinaryReader = New BinaryReader(file.OpenRead())
                bData = br.ReadBytes(br.BaseStream.Length)
                'Dim ms As MemoryStream = New MemoryStream(bData, 0, bData.Length)

                Me.Media.FileName = file.Name
                Me.Media.File = bData
                br.Close()
            End If
        End Sub

        Private Function SelectFile()
            Dim result As FileInfo = Nothing
            Dispatchers.Main.Invoke(
            Sub()
                Dim dlg = New OpenFileDialog()
                If dlg.ShowDialog = True Then
                    result = dlg.File
                End If
            End Sub)

            SelectFile = result
        End Function

        Private Sub OpenWith_Execute()
            ' Write your code here.
            If Not System.Windows.Application.Current.HasElevatedPermissions Then
                Throw New NotSupportedException("Must run with elevated permissions")
            End If

            ' write document to temp file with unique name
            Dim tempFile = GetTempFileName(Me.Media.FileName)
            File.WriteAllBytes(tempFile, Me.Media.File)

            ' open the temp file using Shell Object
            Dim shell = AutomationFactory.CreateObject("WScript.Shell")
            shell.Run(ChrW(34) + tempFile + ChrW(34)) ' must enclose in quotes
        End Sub

        Private Function GetTempFileName(ByVal fileName As String)
            ' create temp folder in My Documents
            Dim tempFolder = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyTempDocuments")
            If Not Directory.Exists(tempFolder) Then
                Directory.CreateDirectory(tempFolder)
            End If

            ' generate unique file name while retaining file extension
            GetTempFileName = System.IO.Path.Combine(tempFolder, String.Format("{0}.{1}", Guid.NewGuid(), fileName))
        End Function

        Private Sub ExportCSV_ControlAvailable(sender As Object, e As ControlAvailableEventArgs)
            RemoveHandler Me.FindControl("ExportCSV").ControlAvailable, AddressOf ExportCSV_ControlAvailable
            Dim Button = DirectCast(e.Control, Button)
            AddHandler Button.Click, AddressOf ExportCSV_Click

            'On Error Resume Next
            'AddHandler CType(e.Control, System.Windows.Controls.Button).GotFocus, AddressOf ExportCSV_Click

        End Sub

        Private Sub ExportCSV_Click(sender As Object, e As System.Windows.RoutedEventArgs)
            'Dim dialog = New SaveFileDialog()
            'dialog.Filter = "Comma Separated Values (*.pdf)|*.pdf"
            'If dialog.ShowDialog() = True Then
            '
            'Using bstream As New BinaryWriter(dialog.OpenFile())
            'Dim pdf As Byte() = Me.Media.File
            'bstream.Write(pdf)
            'bstream.Close()
            'Me.ShowMessageBox("PDF File Created Successfully. ", "PDF Export", MessageBoxOption.Ok)
            'End Using
            'End If

            Dim dlg = New SaveFileDialog()
            dlg.Filter = "PDF (*.pdf)|*.pdf"
            If dlg.ShowDialog = True Then
                Dim stream = dlg.OpenFile
                Using (stream)
                    ' save original uploaded File
                    stream.Write(Me.Media.File, 0, Me.Media.File.Length)
                End Using
            End If


        End Sub

        Private Sub MediaDetail_Created()
            Dim CSVButton = Me.FindControl("ExportCSV")
            AddHandler CSVButton.ControlAvailable, AddressOf ExportCSV_ControlAvailable
        End Sub
    End Class

End Namespace